<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
  <link rel="stylesheet" href="../../styles/common.css"/>
  <link rel="stylesheet" href="../../styles/page.css"/>
  <style>
    #member-app .notAdmin::after {
      border: 0 !important;

    }
  </style>
</head>
<body>
<div class="dashboard-container" id="member-app">
  <div class="container">
    <div class="tableBar">
      <el-input
              v-model="input"
              placeholder="书名"
              style="width: 250px"
              clearable
              @keyup.enter.native="handleQuery"
      >
        <i
                slot="prefix"
                class="el-input__icon el-icon-search"
                style="cursor: pointer"
                @click="handleQuery"
        ></i>
      </el-input>
    </div>
    <el-table
            :data="tableData"
            stripe
            class="tableBox"
            @selection-change="handleSelectionChange"
    >
      <el-table-column
              type="selection"
              width="25"
      ></el-table-column>
      <el-table-column
              prop="index"
              label="ID"
      ></el-table-column>
      <el-table-column prop="image" label="图片" align="center">
        <template slot-scope="{ row }">
          <el-image style="height: 40px; border:none;cursor: pointer;"
                    :src="getImage(row.image)"
                    :preview-src-list="[ `/common/download?name=${row.image}` ]">
            <div slot="error" class="image-slot">
              <img src="./../../images/icons/btn_back@2x.png"
                   style="width: auto; height: 40px; border:none;">
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
              prop="name"
              label="图书名称"
      ></el-table-column>
      <el-table-column
              prop="author"
              label="作者"
      ></el-table-column>
      <el-table-column
              prop="typeName"
              label="图书类型"
      ></el-table-column>
      <el-table-column
              width="140"
              prop="brief"
              label="图书描述"
      ></el-table-column>
      <el-table-column
              width="140"
              prop="createTime"
              :formatter="dataFormat"
              label="创建时间"
      >
      </el-table-column>
      <el-table-column
              width="140"
              prop="updateTime"
              :formatter="dataFormat"
              label="修改时间"
      ></el-table-column>
      <el-table-column label="图书状态">
        <template slot-scope="scope">
          <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="changeStatus(scope.row.id)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
              label="操作"
              width="100"
              align="center"
      >
        <template slot-scope="scope">
          <el-button
                  type="text"
                  size="small"
                  class="blueBug"
                  @click="hotBookHandle(scope.row.id)"
                  :class="{notAdmin:user !== 'admin'}"
          >
            推荐
          </el-button>
          <el-button
                  type="text"
                  size="small"
                  class="delBut"
                  @click="deleteBookHandle('单删',scope.row.id)"
                  :class="{notAdmin:user !== 'admin'}"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
            class="pageList"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="counts"
            :current-page.sync="page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../api/book.js"></script>
<script>
  new Vue({
    el: '#member-app',
    data() {
      return {
        input: '',
        counts: 0,
        page: 1,
        pageSize: 10,
        tableData: [],
        id: '',
        checkList: [],
        status: '',
        index: 0,
        dialogFormVisible: false,
        ruleForm: {
          name: '',
          author: '',
          type: '',
          typeName:'',
          brief: '',
          createTime: '',
          updateTime: '',
          image: '',
          status: '',
          is_delete: ''
        },
        formLabelWidth: '120px'
      }
    },
    computed: {},
    created() {
      this.init()
      this.user = JSON.parse(localStorage.getItem('userInfo')).username
    },
    mounted() {
    },
    methods: {
      //修改时间格式
      dataFormat: function(row){
        //console.log(row);
        let data = row.createTime
        if (data ===null) {
          return ''
        }
        return data[0] + '-' + data[1] + '-' + data[2] + ' ' + data[3] + ':' + data[4] + ':' + data[5]
      },
      changeStatus(id) {
        switchStatus(id).then(res => {
          if (res.code === 200) {
            this.status = res.data.data.status
            console.log(this.status)

            this.$message.success(res.errorMessage)
          }
        }).catch(err => {
          this.$message.error('请求出错了：' + err)
        })
      },
      async init() {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          name: this.input ? this.input : ""
        }
        await getBookList(params).then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records || []
            this.index = (this.page - 1) * this.pageSize;
            // 遍历 tableData 数组，为每个对象设置 index 字段的值
            this.tableData = res.data.records.map((item, index) => {
              item.index = this.index + index + 1;
              return item;
            });
            this.counts = res.data.total
          }
        }).catch(err => {
          this.$message.error('请求出错了：' + err)
        })

      },
      handleQuery() {
        this.page = 1;
        this.init();
      },
      hotBookHandle(id) {
        this.$confirm('确认推荐该图书, 是否继续?', '确定推荐', {
          'confirmButtonText': '确定',
          'cancelButtonText': '取消',
        }).then(() => {
          hotBook(id).then(res => {
            if (res.code === 200) {
              this.$message.success('推荐成功！')
              this.handleQuery()
            } else {
              this.$message.error(res.errorMessage|| '操作失败')
            }
          }).catch(err => {
            this.$message.error('请求出错了：' + err)
          })
        })
      },
      //删除
      deleteBookHandle(type, id) {
        if (type === '批量' && id === null) {
          if (this.checkList.length === 0) {
            return this.$message.error('请选择删除对象')
          }
        }
        this.$confirm('确认删除该图书, 是否继续?', '确定删除', {
          'confirmButtonText': '确定',
          'cancelButtonText': '取消',
        }).then(() => {
          deleBook(type === '批量' ? this.checkList.join(',') : id).then(res => {
            if (res.code === 200) {
              this.$message.success(res.data)
              this.handleQuery()
            } else {
              this.$message.error(res.errorMessage || '操作失败')
            }
          }).catch(err => {
            this.$message.error('请求出错了：' + err)
          })
        })
      },
      getImage(image) {
        return `/common/download?name=${image}`
      },
      // 全部操作
      handleSelectionChange(val) {
        let checkArr = []
        val.forEach((n) => {
          checkArr.push(n.id)
        })
        this.checkList = checkArr
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.init()
      },
      handleCurrentChange(val) {
        this.page = val
        this.init()
      },
    }
  })
</script>
</body>
</html>